package net.m510.autosurfer.core.process;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.logging.Logger;

import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.nodes.Document;

public abstract class AbstractPostProcess<T> extends AbstractSurfProcess<T> {
	protected Logger log = Logger.getLogger(AbstractPostProcess.class.getName());
	
	public AbstractPostProcess() {
		super();
	}

	public AbstractPostProcess(CloseableHttpClient client, HttpClientContext context) {
		super(client, context);
	}
	
	@Override
	public T process(Document doc) throws IOException {
		// リクエスト生成
		HttpPost req = new HttpPost(getUri(doc));
		//　リクエストパラメータ設定
		List<NameValuePair> params = getRequestParameters(doc);
		req.setEntity(new UrlEncodedFormEntity(params,defaultCharset));
		
		// レスポンスハンドラ生成
		ResponseHandler<T> handler = getResponseHandler();
		//　リクエスト送信
		log.fine("request entity : " + EntityUtils.toString(req.getEntity(), defaultCharset));
		T out = client.execute(req, handler,context);
		
		return out;
	}
	
	protected abstract List<NameValuePair> getRequestParameters(Document doc);
	protected abstract URI getUri(Document doc);
	protected abstract ResponseHandler<T> getResponseHandler();

}
